<template>
	<view class="body">
		<view class="headSearch">
			<view class="contronBox">
				<view class="score">可用家庭积分:{{ state.allPoint }}</view>
				<!-- <view class="history">兑换记录</view> -->
			</view>
			<view class="searchBox">
				<!-- <image class="searchIcon" src="/static/icons/search.png" mode="aspectFit"></image> -->
				<input type="text" placeholder="输入商品名称或积分" v-model="searchKey" />
			</view>
		</view>

		<!-- 积分兑换商品区域 -->
		<view class="exchange-section">
			<view class="section-title">积分兑换商品</view>
			<!-- <view class="category-tabs">
				<text class="tab active">食品</text>
				<text class="tab">日用品</text>
			</view> -->

			<view class="products-grid">
				<view class="product-item" v-for="(item, index) in products" :key="index" @click="toExchange(item)">
					<image class="product-image" :src="item.item_pic" mode="aspectFit"></image>
					<view class="product-info">
						<text class="product-name">{{ item.item_name }}</text>
						<view class="points-tag">{{ item.item_jackpoint }}积分</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	reactive,
	ref,
	onMounted,
	watch
} from "vue";
import {
	onLoad
} from "@dcloudio/uni-app";
import {
	request,
	formatDateTime
} from "../../js/util.js";
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import {
	onShow
} from '@dcloudio/uni-app'

// 搜索关键词
const searchKey = ref('');

// 商品数据
const products = ref([]);
const allProducts = ref([]); // 存储所有商品数据
const state = reactive({
	allPoint: 0
});

// 获取商品列表
const getProductList = async () => {
	try {

		const arr = Array.from({
			length: 9
		}, (_, i) => i + 1);
		// 由于 yield 不能在 map 回调中使用，需用 for 循环替换
		let list = [];
		for (let x of arr) {
			let submitData = {
				condition: {
					item_jackpoint: x.toString()
				}
			};
			console.log("submitData:", submitData);
			const data = await request("selectItem", submitData);
			console.log("getShop", data);
			list = [...list, ...data.result];
		}
		allProducts.value = list || []
		filterProducts(); // 获取数据后进行筛选
		// if (result.status) {
		// 	allProducts.value = result.result || [];
		// 	filterProducts(); // 获取数据后进行筛选
		// } else {
		// 	uni.showToast({
		// 		title: result.message || '获取商品列表失败',
		// 		icon: 'none'
		// 	});
		// }
	} catch (error) {
		console.error('获取商品列表失败:', error);
		uni.showToast({
			title: '获取商品列表失败',
			icon: 'none'
		});
	}
};

//获取积分
const getPointList = async () => {
	let searchId = uni.getStorageSync("userid")
	let submitData = {
		condition: {
			user_id: searchId,
		}
	};
	const data = await request("selectJackpoint", submitData);
	console.log("selectJackpoint", data)
	if (data.result) {
		let allPoint = 0
		data.result.map(x => {
			allPoint += Number(x.jackpoint)
		})
		state.allPoint = allPoint
	} else {
		uni.showToast({
			title: "查询失败",
			icon: "error",
		});
	}
};


// 添加防抖函数
const debounce = (fn, delay = 300) => {
	let timer = null;
	return function (...args) {
		if (timer) clearTimeout(timer);
		timer = setTimeout(() => {
			fn.apply(this, args);
		}, delay);
	};
};

//跳转到兑换表单
const toExchange = (item) => {
	uni.navigateTo({
		url: `/pages/exchange/exchange?id=${item._id}&url=${item.item_pic}`,
	});
}

// 筛选商品
const filterProducts = () => {
	if (!searchKey.value) {
		products.value = allProducts.value;
		return;
	}

	products.value = allProducts.value.filter(product =>
		product.item_name.toLowerCase().includes(searchKey.value.toLowerCase()) ||
		product.item_jackpoint.toString().includes(searchKey.value)
	);
};

// 创建防抖搜索方法
const debouncedSearch = debounce(filterProducts, 300);

// 监听搜索关键词变化
watch(() => searchKey.value, () => {
	debouncedSearch();
});

// 页面显示时获取数据
onLoad(() => {
	console.log('111:', 111)
	getPointList();
	getProductList();
});
</script>

<style lang="less">
.body {
	background-color: #f0f0f0;
	min-height: 100vh;
}

.headSearch {
	background-color: #fff;
	padding: 20rpx;

	.contronBox {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;

		.score {
			color: #237804;
		}
	}

	.searchBox {
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 32rpx;
		padding: 15rpx 30rpx;

		.searchIcon {
			width: 32rpx;
			height: 32rpx;
			margin-right: 10rpx;
		}

		input {
			flex: 1;
			font-size: 28rpx;
			background: transparent;
		}
	}
}

.exchange-section {
	margin-top: 20rpx;
	padding: 20rpx;
	background-color: #fff;

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.category-tabs {
		display: flex;
		margin-bottom: 20rpx;

		.tab {
			padding: 10rpx 20rpx;
			margin-right: 20rpx;
			font-size: 28rpx;

			&.active {
				color: #237804;
				border-bottom: 4rpx solid #237804;
			}
		}
	}

	.products-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;

		.product-item {
			background: #fff;
			border-radius: 12rpx;
			overflow: hidden;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
			margin: 20rpx 0;

			.product-image {
				width: 100%;
				height: 300rpx;
				background: #f5f5f5;
			}

			.product-info {
				padding: 20rpx;

				.product-name {
					font-size: 28rpx;
					margin-bottom: 10rpx;
				}

				.points-tag {
					display: inline-block;
					background: #ffe58f;
					color: #d4b106;
					padding: 4rpx 16rpx;
					border-radius: 20rpx;
					font-size: 24rpx;
					margin-left: 10rpx;
				}
			}
		}
	}
}
</style>